<template>
  <div class="depart-user-list-wrapper">
    <div class="depart-user-list-top">
      <div class="search-wrapper f-search-wrapper">
        <el-input placeholder="部门名称" v-model="filterText"/>
      </div>
      <el-tree
          :expand-on-click-node="false"
          auto-expand-parent
          ref="treeRef"
          class="filter-tree"
          :data="departs" highlight-current
          :props="defaultProps"
          default-expand-all
          :filter-node-method="filterNode">
        <template v-slot="{ node, data }">
          <div class="node-item" @dblclick="() => createUnitSelection(data)"
               @click="() => selectUnit(data)">
            {{ data.unitName }}
          </div>
        </template>
      </el-tree>
    </div>
    <div class="depart-user-list-center">
      <el-radio-group v-model="bottomListType" @change="bottomListTypeChange">
        <el-radio label="user">人员</el-radio>
        <el-radio label="position">岗位</el-radio>
        <el-radio label="role">角色</el-radio>
      </el-radio-group>
    </div>
    <div class="depart-user-list-bottom">
      <FList :selected-key="selectedUserId"
             v-loading="loading" @doubleClick="createUserSelection"
             v-show="bottomListType === 'user'"
             size="small" @select="selectUser"
             :data-source="users"
             title-name="realname"/>

      <FList :selected-key="selectedDepartId"
             v-loading="loading" @doubleClick="createDepartPositionSelection"
             v-show="bottomListType === 'position'"
             size="small" @select="selectDepart"
             :data-source="positions"
             title-name="positionName"/>

      <FList :selected-key="selectingRoleId"
             v-loading="loading" @doubleClick="createDepartRoleSelection"
             v-show="bottomListType === 'role'"
             size="small" @select="selectRole"
             :data-source="roles"
             title-name="roleName"/>
    </div>
  </div>
</template>

<script>
import {UserConfig} from '@/components/UserSelectorModal/DefaultUserConfig';
import {guid, isEmpty, listToTrees} from '@/utils/CommonUtils';
import {ElMessageBox} from 'element-plus';
import {getAction} from '@/request/BaseRequest';
import FList from '@/components/FList';

export default {
  name: "DepartUserList",
  components: {FList},
  data() {
    return {
      selectedUserId: undefined,
      selectedDepartId: undefined,
      selectingRoleId: undefined,
      filterText: undefined,
      loading: false,
      defaultProps: {
        children: 'children',
        label: 'unitName',
      },
      bottomListType: 'user',
      departs: [],
      positions: [],
      roles: [],
      users: []
    };
  },
  mounted() {
    this.loadDeparts();
  },
  methods: {
    setDeparts(units) {
      this.departs = listToTrees(units);
    },
    loadDeparts() {
      this.loading = true;
      getAction('/base/baseUnit/query').then(data => {
        if (data.success) {
          if(!data.result) data.result = [];
          this.setDeparts(data.result);
        } else {
          this.$notification.error({message: data.message, result: data.result, duration: 3});
        }
        this.loading = false;
      })
    },
    bottomListTypeChange() {
      this.loadBottomList();
    },
    loadBottomList() {
      if (isEmpty(this.selectingDepart)) {
        return;
      }

      if (this.bottomListType === 'user') {
        this.loadUser();
      }
      if (this.bottomListType === 'position') {
        this.loadPosition();
      }
      if (this.bottomListType === 'role') {
        this.loadRole();
      }
    },
    loadUser() {
      this.loading = true;
      getAction('/base/loadUserByUnitId',
          {unitId: this.selectingDepart.id}).then(data => {
        if (data.success) {
          this.users = data.result;
        } else {
          this.$notification.error({message: data.message, duration: 3});
        }
        this.loading = false;
      })
    },
    createDepartRoleSelection(role) {
      let res = JSON.parse(JSON.stringify(UserConfig));
      res.type = 'role';
      res.roleId = role.id;
      res.roleName = role.roleName;

      res.unitId = this.selectingDepart.id;
      res.unitName = this.selectingDepart.unitName;
      res.id = guid();
      res.configName = `${res.unitName}-${res.roleName}`;

      let depart = this.selectingDepart;
      if (depart.children && depart.children.length >= 1) {
        ElMessageBox.confirm('是否包含下级?', 'Warning', {
          showClose: false,
          confirmButtonText: '包含',
          cancelButtonText: '不包含',
          type: 'info',
        }).then(() => {
          res.configName += '(包含下级)';
          res.containSubUnit = true;
          this.$emit('create', res);
        }).catch(() => {
          res.containSubUnit = false;
          res.configName += '(不包含下级)';
          this.$emit('create', res);
        });
      } else {
        this.$emit('create', res);
      }
    },
    createDepartPositionSelection(position) {
      let res = JSON.parse(JSON.stringify(UserConfig));
      res.type = 'position';
      res.positionId = position.id;
      res.positionName = position.positionName;

      res.unitId = this.selectingDepart.id;
      res.unitName = this.selectingDepart.unitName;
      res.id = guid();
      res.configName = `${res.unitName}-${res.positionName}`;

      let depart = this.selectingDepart;
      if (depart.children && depart.children.length >= 1) {
        ElMessageBox.confirm('是否包含下级?', 'Warning', {
          showClose: false,
          confirmButtonText: '包含',
          cancelButtonText: '不包含',
          type: 'info',
        }).then(() => {
          res.configName += '(包含下级)';
          res.containSubUnit = true;
          this.$emit('create', res);
        }).catch(() => {
          res.containSubUnit = false;
          res.configName += '(不包含下级)';
          this.$emit('create', res);
        });
      } else {
        this.$emit('create', res);
      }
    },
    createUserSelection(user) {
      let res = JSON.parse(JSON.stringify(UserConfig));
      res.type = 'user';
      res.userId = user.id;
      res.userName = user.realname;
      res.configName = user.realname;
      res.id = guid();
      this.$emit('create', res);
    },
    selectRole(role) {
      this.selectingRoleId = role.id;
    },
    selectDepart(depart) {
      this.selectedDepartId = depart.id;
    },
    selectUser(user) {
      this.selectedUserId = user.id;
    },
    loadPosition() {
      this.loading = true;
      getAction('/base/loadPositionByUnitId', {unitId: this.selectingDepart.id}).then(data => {
        if (data.success) {
          this.positions = data.result;
        } else {
          this.$notification.error({message: data.message, duration: 3});
        }
        this.loading = false;
      })
    },
    loadRole() {
      this.loading = true;
      getAction('/base/loadRoleByUnitId', {unitId: this.selectingDepart.id}).then(data => {
        if (data.success) {
          this.roles = data.result;
        } else {
          this.$notification.error({message: data.message, duration: 3});
        }
        this.loading = false;
      })
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.unitName.includes(value);
    },
    selectUnit(depart) {
      this.selectingDepart = depart;
      this.loadBottomList();
    },
    createUnitSelection(depart) {
      let userConfig = JSON.parse(JSON.stringify(UserConfig));
      userConfig.type = 'unit';
      userConfig.unitId = depart.id;
      userConfig.unitName = depart.unitName;
      userConfig.configName = depart.unitName;
      userConfig.id = guid();
      userConfig.containSubUnit = true;

      if (depart.children && depart.children.length >= 1) {
        ElMessageBox.confirm('是否包含下级单位?', 'Warning', {
          showClose: false,
          confirmButtonText: '包含',
          cancelButtonText: '不包含',
          type: 'info',
        }).then(() => {
          userConfig.configName += '(包含下级)';
          userConfig.containSubUnit = true;
          this.$emit('create', userConfig);
        }).catch(() => {
          userConfig.containSubUnit = false;
          userConfig.configName += '(不包含下级)';
          this.$emit('create', userConfig);
        });
      } else {
        this.$emit('create', userConfig);
      }
    }
  },
  watch: {
    filterText(filterText) {
      this.$refs.treeRef.filter(filterText);
    },
  }
};
</script>

<style scoped>

.depart-user-list-wrapper {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.depart-user-list-top,
.depart-user-list-bottom {
  flex: 0.5;
  overflow: auto;
  background: white;
}

.depart-user-list-center {
  border-color: rgb(220, 223, 230);
  border-width: 1px 0 1px 0;
  border-style: solid;
  padding-left: 10px;
}

.search-wrapper {
  position: sticky;
  top: 0;
  left: 0;
  z-index: 20;
}

.node-item {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
}
</style>
